//权限数据
var privilegeStore=new Ext.data.Store({
	proxy : new Ext.data.HttpProxy({
		url : 'showPrivilegeList',
		method : 'post'
	}),
	reader : new Ext.data.JsonReader({
		root : 'Privilege',
		totalProperty : 'totalPrivilege',
		id : 'id'
	}, [{
		name : 'id'
	}, {
		name : 'name'
	}, {
		name : 'company'
	}, {
		name : 'project'
	}, {
		name : 'department'
	}, {
		name : 'version'
	}, {
		name : 'type'
	}, {
		name : 'read'
	}, {
		name : 'delete'
	}, {
		name : 'modify'
	}]),
	remoteSort: false
});

//表格列模型
var privilegesm=new Ext.grid.CheckboxSelectionModel ({singleSelect : false});
var privilegeColumnModel=new Ext.grid.ColumnModel([privilegesm,
	new Ext.grid.RowNumberer(),
	{
		header : '文件名',
		width : 100,
		dataIndex : 'name',
		sortable : true,
		id : 'name'
	}, {
		header : '权限所属公司',
		width : 120,
		dataIndex : 'company',
		sortable : true,
		align : 'center'
	}, {
		header : '项目',
		width : 60,
		dataIndex : 'project',
		sortable : true,
		align : 'right'
	}, {
		header : '文件所属部门',
		width : 60,
		dataIndex : 'department',
		sortable : true,
		align : 'center'
	}, {
		header : '版本',
		width : 60,
		dataIndex : 'version',
		sortable : true,
		align : 'center'
	}, {
		header : '类型',
		width : 60,
		dataIndex : 'type',
		sortable : true,
		align : 'center',
		renderer:function(value, cellmeta, record){
			var typemap=[['1','流程模型']
					,['2','功能模型']
					,['3','组织模型']
					,['4','业务对象模型']
					,['5','epc模型']
					,['6','权限模型']
					,['7','角色模型']];
			return typemap[value-1][1];
		}
	}, {
		header :"查看权限",
		dataIndex :"read",
		sortable :true,
		width :100,	
		editable: true,
		editor :new Ext.form.ComboBox( {
		    id :"read_combo",
		    store :new Ext.data.SimpleStore({   
	            fields: ['read','text'],
	            data: [[0,'禁止'],[1,'允许']]   
	        }),
		    valueField :"read",
			displayField :"text",
			editable:true,
			forceSelection :true,
			typeAhead :true,
			triggerAction :'all',
			selectOnFocus :true,// 用户不能自己输入,只能选择列表中有的记录
			allowBlank :false,
			mode: 'local'
		}),
		renderer : function(value, cellmeta, record) {		
			//获取当前id="combo_process"的comboBox选择的值
			var dc=Ext.getCmp('read_combo');
			var index = this.editor.store.find(Ext.getCmp('read_combo').valueField, value);
			var record = this.editor.store.getAt(index);
			var displayText = "";
			// 如果下拉列表没有被选择，那么record也就不存在，这时候，返回传进来的value，
			// 而这个value就是grid的deal_with_name列的value，所以直接返回
			if (record == null) {			
				//返回默认值，这是与网上其他解决办法不同的。这个方法才是正确的。我研究了很久才发现。
				displayText = value;			
			} else {
				displayText = record.data.text;//获取record中的数据集中的process_name字段的值
			}
			return displayText;
		}
	}, {
		header :"删除权限",
		dataIndex :"delete",
		sortable :true,
		width :100,	
		editable: true,
		editor :new Ext.form.ComboBox( {
		    id :"delete_combo",
		    store :new Ext.data.SimpleStore({   
	            fields: ['delete','text'],
	            data: [[0,'禁止'],[1,'允许']]   
	        }),
		    valueField :"delete",
			displayField :"text",
			editable:true,
			forceSelection :true,
			typeAhead :true,
			triggerAction :'all',
			selectOnFocus :true,// 用户不能自己输入,只能选择列表中有的记录
			allowBlank :false,
			mode: 'local'
		}),

		renderer : function(value, cellmeta, record) {
			var dc=Ext.getCmp('delete_combo');
			var index = this.editor.store.find(Ext.getCmp('delete_combo').valueField, value);
			var record = this.editor.store.getAt(index);
			var displayText = "";
			if (record == null) {
				displayText = value;
			
			} else {
				displayText = record.data.text;//获取record中的数据集中的process_name字段的值
			}
			return displayText;
		}
	}, {
		header :"修改权限",
		dataIndex :"modify",
		sortable :true,
		width :100,	
		editable: true,
		editor :new Ext.form.ComboBox({
		    id :"modify_combo",
		    store :new Ext.data.SimpleStore({   
	            fields: ['modify','text'],
	            data: [[0,'禁止'],[1,'允许']]   
	        }),
		    valueField :"modify",
			displayField :"text",
			editable:false,
			forceSelection :true,
			typeAhead :true,
			triggerAction :'all',
			selectOnFocus :true,// 用户不能自己输入,只能选择列表中有的记录
			allowBlank :false,
			mode: 'local'
		}),
		renderer : function(value, cellmeta, record) {		
			//获取当前id="combo_process"的comboBox选择的值
			var dc=Ext.getCmp('modify_combo');
			var index = this.editor.store.find(Ext.getCmp('modify_combo').valueField, value);
			var record = this.editor.store.getAt(index);
			var displayText = "";
			// 如果下拉列表没有被选择，那么record也就不存在，这时候，返回传进来的value，
			// 而这个value就是grid的deal_with_name列的value，所以直接返回
			if (record == null) {
			
				//返回默认值，这是与网上其他解决办法不同的。这个方法才是正确的。我研究了很久才发现。
				displayText = value;
			
			} else {
				displayText = record.data.text;//获取record中的数据集中的process_name字段的值
			}
			return displayText;
		}
	}]
);

//模型-权限列表
var privilegeList=new Ext.grid.EditorGridPanel({
	enableColumnResize : true,
	border : true,
	clicksToEdit:1,
	enableColumnMove : true,
	enableHdMenu : false,
	stripeRows: true, //显示斑马线
	loadMask: true,
	autoHeight:true,
	bodyStyle:'width:100%',
    autoWidth:true,
    editable:true,
    sm : privilegesm,
	//columns : privilegeColumnModel,
	bbar: new Ext.PagingToolbar({//下面的分页条
        pageSize: 15,
        store: privilegeStore,
        displayInfo: true,
        displayMsg: '当前显示第 {0} 条到 {1} 条记录，一共 {2} 条',
        emptyMsg: "没有记录",
        lastText:"尾页",   
        nextText :"下一页",   
        prevText :"上一页",   
        firstText :"首页",   
        refreshText:"刷新页面"        
    }),
    tbar:[{
		xtype:'button',
		iconCls : 'db-icn-upload_',
		width:100,
		text:'提交修改',
		handler:submitModifiedPrivilege
	},
		{xtype : "tbseparator"},
	{
		text:'设置选中项查看权限',
		menu:new Ext.menu.Menu({
			items:[{
				text:'禁止',
				handler:function(){
					setSelectedPrivilege('read',0);
				}
			},{
				text:'允许',
				handler:function(){
					setSelectedPrivilege('read',1);
				}
			},{
				text:'反选',
				handler:function(){
					setSelectedPrivilege('read',-1);
				}
			}]
		})
	},
		{xtype : "tbseparator"},
	{
		text:'设置选中项删除权限',
		menu:new Ext.menu.Menu({
			items:[{
				text:'禁止',
				handler:function(){
					setSelectedPrivilege('delete',0);
				}
			},{
				text:'允许',
				handler:function(){
					setSelectedPrivilege('delete',1);
				}
			},{
				text:'反选',
				handler:function(){
					setSelectedPrivilege('delete',-1);
				}
			}]
		})
	},
		{xtype : "tbseparator"},
	{
		text:'设置选中项修改权限',
		menu:new Ext.menu.Menu({
			items:[{
				text:'禁止',
				handler:function(){
					setSelectedPrivilege('modify',0);
				}
			},{
				text:'允许',
				handler:function(){
					setSelectedPrivilege('modify',1);
				}
			},{
				text:'反选',
				handler:function(){
					setSelectedPrivilege('modify',-1);
				}
			}]
		})
	}],
	cm : privilegeColumnModel,
	store : privilegeStore
	
});

//提交修改过的权限
var submitted=0;
function submitModifiedPrivilege(){
	submitted=0;
	var records=privilegeStore.getModifiedRecords();
	for(var i=0;i<records.length;i++){
		var rec=records[i];
		var id=rec.get('id');
		var readop=rec.get('read');
		var deleteop=rec.get('delete');
		var modifyop=rec.get('modify');
		Ext.Ajax.request({
			url: 'updatePrivilege.action?method=updatePrivilege&id='+id
				+'&readop='+readop
		   		+'&deleteop='+deleteop
		   		+'&modifyop='+modifyop,				   	
		   	success: function(res,opt){		   		
		   		submitted++;
		   		rec.commit();	
		   		if(submitted>=records.length){
		   			Ext.Msg.alert('消息','提交成功！');
		   		}
		   	},
		   	failure: function(){
		   		
		   	}
		});
	}	
}

//按文件名搜索框
var fileNameField=new Ext.form.TextField({
	id:'pfileName_txt',
	name:'fileName',
	width:100,
	allowblank:false,
	enableKeyEvents:true
});

//按公司搜索框
var companyStore = new Ext.data.Store({
	proxy : new Ext.data.HttpProxy({
		url : 'showAllCompanies.action?method=showAllCompanies',
		method : 'post'
	}),
	reader : new Ext.data.JsonReader({
		root : "Company",
		totalProperty : "totalCompany",
		id : "id"
	}, [ {
		name : 'id'
	}, {
		name : 'name'
	}])
});
companyStore.load();

var companyCombo=new Ext.form.ComboBox({
    id:'pcompany_search_cmb',
	name:'company',
	fieldLabel:'部门',
	allowblank:true,
	emptyText: '请选择',
	mode: 'local',   
	width:100,
    triggerAction: 'all',   
    valueField: 'id',   
    displayField: 'name',   
    editable:false,  
    selectOnFocus : false,  
    forceSelection : false,
    store: companyStore
});

//按项目搜索
var projectField=new Ext.form.TextField({
    id:'pproject_txt',
	name:'project',
	width:100,
	allowblank:false,
	enableKeyEvents:true	    	    	 
});

//按部门搜索下拉框
var departmentPrivilegeStore = new Ext.data.Store({
	proxy : new Ext.data.HttpProxy({
		url : 'showDepartment.action?method=showDepartment',
		method : 'post'
	}),
	reader : new Ext.data.JsonReader({
		root : "Department",
		totalProperty : "totalDepartment",
		id : "id"
	}, [ {
		name : 'id'
	}, {
		name : 'enName'
	}, {
		name : 'cnName'
	}, {
		name : 'parentName'
	}])
});

departmentPrivilegeStore.load();
var departmentCombo=new Ext.form.ComboBox({
    id:'department_search_cmb',
	name:'department',
	fieldLabel:'部门',
	emptyText: '请选择',
	mode: 'local',   
	width:100,
    triggerAction: 'all',   
    valueField: 'id',   
    displayField: 'cnName',   
    editable:false,  
    selectOnFocus : false,  
    forceSelection : false,
    allowBlank : true,
    store: departmentPrivilegeStore
});


//按部门搜索下拉框
var departmentPrivilegeStore2 = new Ext.data.Store({
	proxy : new Ext.data.HttpProxy({
		url : 'showDepartment.action?method=showDepartment',
		method : 'post'
	}),
	reader : new Ext.data.JsonReader({
		root : "Department",
		totalProperty : "totalDepartment",
		id : "id"
	}, [ {
		name : 'id'
	}, {
		name : 'enName'
	}, {
		name : 'cnName'
	}, {
		name : 'parentName'
	}])
});

departmentPrivilegeStore2.load();
var departmentPrivilegeCombo=new Ext.form.ComboBox({
    id:'department_search_cmb2',
	name:'department',
	fieldLabel:'部门',
	emptyText: '请选择',
	mode: 'local',   
	width:100,
    triggerAction: 'all',   
    valueField: 'id',   
    displayField: 'cnName',   
    editable:false,  
    selectOnFocus : false,  
    forceSelection : false,
    allowBlank : true,
    store: departmentPrivilegeStore2
});

//按版本搜索
var versionField=new Ext.form.TextField({
    id:'pversion_txt',
	name:'version',
	width:100,
	allowblank:false,
	enableKeyEvents:true,
	listeners : { 
        "keyup" : function() { 
        	var c=Ext.getCmp('version_txt');
        	fileInfoList.updateData(selected_row,c.name,c.getValue()); 
        } 
	}		    	    	 
});

//按类型搜索下拉框
var typeCombo=new Ext.form.ComboBox( {
    id :"ptype_search_cmb",
    name:'type',
    allowblank:true,
    fieldLabel:'类型',
	emptyText: '请选择',
	mode: 'local',  
	width:100,
    triggerAction: 'all',   
    valueField: 'id',   
    displayField: 'text',   
    editable:false,  
    selectOnFocus : false,  
    forceSelection : false,
	store: new Ext.data.SimpleStore({   
        fields: ['id','text'],
        data: [['1','流程模型'],['2','功能模型'],['3','组织模型'],['4','业务对象模型'],['5','epc模型'],['6','权限模型'],['7','角色模型']]   
    })
});

//权限设置面板
var privilegePanel=new Ext.Panel({
	title:'权限设置',
	id:'privilege-panel',
	layout:'fit', 
	items:[privilegeList],
	tbar:[{
		xtype:'button',
		iconCls : 'search',
		width:60,
		text:'显示全部',
		handler:showAllPrivileges
	},{
		xtype:'button',
		iconCls : 'search',
		width:60,
		text:'搜索',
		handler:searchPrivilege
	},
	    new Ext.Toolbar.TextItem('文件名:'),
	    fileNameField,
	    {xtype : "tbseparator"},
	    new Ext.Toolbar.TextItem('权限所属公司:'),
	    companyCombo,
	    {xtype : "tbseparator"},
	    new Ext.Toolbar.TextItem('项目:'),
	    projectField,
	    {xtype : "tbseparator"},
	    new Ext.Toolbar.TextItem('版本:'),
	    versionField,
	    {xtype : "tbseparator"},
	    new Ext.Toolbar.TextItem('类型:'),
	    typeCombo,
	    {xtype : "tbseparator"},
	    new Ext.Toolbar.TextItem('文件所属部门:'),
	    departmentPrivilegeCombo
	]
});

//根据关键字搜索
function searchPrivilege(){
	var fileName=fileNameField.getValue();
	var project=projectField.getValue();
	var company=companyCombo.getValue();
	var version=versionField.getValue();
	var type=typeCombo.getValue();
	var department=departmentPrivilegeCombo.getValue();
	var newurl='searchPrivilege.action?method=searchPrivilege&fileName='+encodeURIComponent(fileName)
	+'&project='+encodeURIComponent(project)
		+'&company='+company
		+'&type='+type
		+'&department='+department
		+'&version='+encodeURIComponent(version);
	privilegeStore.proxy=new Ext.data.HttpProxy({
		url : newurl,
		method : 'post'
	});
	privilegeStore.load({ params: { start: 0, limit: 15} });
	//在执行完成之后清除combox中的内容
	departmentCombo.clearValue();
	companyCombo.clearValue();
	typeCombo.clearValue();
}

//显示所有权限
function showAllPrivileges(){
	privilegeStore.proxy=new Ext.data.HttpProxy({
		url : 'showPrivilegeList',
		method : 'post'
	});
	privilegeStore.load({ params: { start: 0, limit: 15} });
}

/*设置选中的记录的指定权限
 *field:字段名
 *newp:1,允许；0，禁止；-1，反选
 */
function setSelectedPrivilege(field,newp){
	var records=privilegeList.getSelectionModel().getSelections();
	for(var i=0;i<records.length;i++){
		var rec=records[i];
		if(newp==-1){
			rec.set(field,1-rec.get(field));
		}else if(newp==1 || newp==0){
			rec.set(field,newp);
		}
	}
}

//验证操作权限
function authenticate(fileInfoId,op,callback){
	Ext.Ajax.request({
		url: 'checkPrivilege.action?method=checkPrivilege&fileInfoId='+fileInfoId
			+'&op='+op,				   	
	   	success: function(res,opt){
	   		var obj=Ext.util.JSON.decode(res.responseText);
	   		var success=obj.success;
	   		if(success){
	   			callback();
	   		}else{
	   			Ext.Msg.alert('操作失败','你没有进行此操作的权限！');
	   		}
	   	},
	   	failure: function(){
	   		
	   	}
	});
}